/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BoxLayout;
import core.IMAPMIDlet;
import core.MessageManager;
import core.NotificationManager;
import core.OrderManager;
import core.RuntimeData;
import core.ScreenEngine;
import core.Settings;
import datamodel.Message;
import datamodel.Order;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import network.Connection;
import network.PacketBuilder;
import network.packets.DriverBalanceChange;
import network.packets.DriverParkingPositionResponce;
import network.packets.FilteredTaxiParkingsResponce;
import network.packets.GetCSBalanceResponce;
import network.packets.LoginResponce;
import network.packets.PPCSettingsResponce;
import network.packets.Packet;
import network.packets.PreOrdersResponse;
import network.packets.RegisterOnTaxiParkingResponce;
import network.packets.RelayCommunicationResponce;
import network.packets.SettingsXML;
import network.packets.UnRegisterOnTaxiParkingResponce;
import utils.StringUtils;
import view.additional.CompletedOrderListRenderer;

/**
 *
 * @author Kvest
 */
public class MainForm extends BasicForm implements OrderManager.OrderEvents, MessageManager.MessageEvents
{
    private static final int PN_GET_PREORDERS = -1;
    private static final int PN_UPDATE_PREORDERS_COUNT = 7;
    
    private static final int SHOW_INFO_TIMEOUT = 10000;
    
    private static final int MENU_COMMAND_ID = 0;
    private static final int LOOK_COMMAND_ID = 1;
    private static final int CENTER_COMMAND_ID = 2;
    
    public static final int ICONS_SIZE = 14;
    
    private static Image efirIcon;
    private static Image prelimIcon;
    private static Image currentIcon;
    private static Image completeIcon;
    private static Image iconesIcon;
    
    private OrderManager orderManager;
    private MessageManager messageManager;
    
    private boolean showBalance = false;
    
    public static void setEfirIcon(Image value)
    {
        efirIcon = value;
    }
    
    public static void setPrelimIcon(Image value)
    {
        prelimIcon = value;
    }
    
    public static void setCurrentIcon(Image value)
    {
        currentIcon = value;
    }
    
    public static void setCompleteIcon(Image value)
    {
        completeIcon = value;
    }
    
    public static void setIconsIcon(Image value)
    {
        iconesIcon = value;
    }
    
    private RuntimeData runtimeData;
    
    private Label stateLabel;
    private Label filterLabel;
    private Label balanceLabel;
    private String balanceText;
    
    private Label efirLabel;
    private Label prelimLabel;
    private Label currentLabel;
    private Label completeLabel;
    private Label messagesLabel;
    
    private String efirLabelText;
    private String prelimLabelText;
    private String currentLabelText;
    private String completeLabelText;
    private String messagesLabelText;
    private String filterLabelText;
    
    private OrdersListForm efirList;
    private OrdersListForm prelimList;
    private OrdersListForm currentList;
    private OrdersListForm completeList;
    private MessagessListForm messagesList;
    
    private OrderForm canceledOrderForm;
    private OrderForm completedOrderForm;
    private OrderForm newOrderForm;
    private OrderForm orderChangedForm;
    
    private UpdateForm updateForm;
    private MenuForm menuForm;
    
    private Timer preordersUpdateTimer;
    
    public MainForm()
    {
        super("main");
        
        init();
        
        runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
        orderManager = IMAPMIDlet.getMidlet().getOrderManager();
        messageManager = IMAPMIDlet.getMidlet().getMessageManager();
        
        registerNetworkNotifiers();
        
        registerListeners();
    }
    
    private void init()
    {
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        setCyclicFocus(false);
        
        stateLabel = new Label("not_opend");
        stateLabel.setUIID("InfoLabel");
        stateLabel.setFocusable(false);
        stateLabel.setEndsWith3Points(true);
        addComponent(stateLabel);
        
        filterLabel = new Label("filter");
        filterLabelText = filterLabel.getText();
        filterLabel.setText("");
        filterLabel.setUIID("InfoLabel");
        filterLabel.setFocusable(false);
        filterLabel.setEndsWith3Points(true);
        addComponent(filterLabel);
        
        efirLabel = new Label("in_efir");
        efirLabelText = efirLabel.getText();
        efirLabel.setIcon(efirIcon);
        efirLabel.setFocusable(true);  
        efirLabel.setEndsWith3Points(true);
        addComponent(efirLabel);
        
        prelimLabel = new Label("prelim");
        prelimLabelText = prelimLabel.getText();
        prelimLabel.setIcon(prelimIcon);
        prelimLabel.setFocusable(true);  
        prelimLabel.setEndsWith3Points(true);
        addComponent(prelimLabel);

        currentLabel = new Label("current");
        currentLabelText = currentLabel.getText();
        currentLabel.setIcon(currentIcon);
        currentLabel.setFocusable(true);  
        currentLabel.setEndsWith3Points(true);
        addComponent(currentLabel);

        completeLabel = new Label("complete");
        completeLabelText = completeLabel.getText();
        completeLabel.setIcon(completeIcon);
        completeLabel.setFocusable(true);  
        completeLabel.setEndsWith3Points(true);
        addComponent(completeLabel);
        
        messagesLabel = new Label("mess");
        messagesLabelText = messagesLabel.getText();
        messagesLabel.setIcon(iconesIcon.subImage(0, 0, ICONS_SIZE, ICONS_SIZE, true));
        messagesLabel.setFocusable(true);  
        messagesLabel.setEndsWith3Points(true);
        addComponent(messagesLabel);
        
        balanceLabel = new Label("balance_text");
        balanceText = balanceLabel.getText();
        balanceLabel.setText(StringUtils.replace(balanceText, "?", "0.0"));
        balanceLabel.setUIID("InfoLabel");
        balanceLabel.setFocusable(false);
        balanceLabel.setEndsWith3Points(true);
        addComponent(balanceLabel);
        
        //Команды
        Command centerCommand = new Command("", CENTER_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {
                lookAction();
                
                evt.consume();
            }
        };
        addCommand(centerCommand);
        
        Command menu = new Command("menu", MENU_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {          
                //Показываем форму "Меню"
                showMenuForm();
                
                evt.consume();
            }
        };
        addCommand(menu);
        
        Command look = new Command("look", LOOK_COMMAND_ID)
        {
            public void actionPerformed(ActionEvent evt)
            {                
                lookAction();
                
                evt.consume();
            }
        };
        addCommand(look);
    }
    
    private void startPreordersUpdateTimer()
    {         
        //Если таймер запущен - останавливаем
        if (preordersUpdateTimer != null)
        {
            try
            {
                preordersUpdateTimer.cancel();
            }catch(Exception ex){}
        }
        
        //Запускаем обновление количества пред. заказов
        int period = Settings.getSettings().getPreordersUpdatePeriod() * 60 * 1000; //Сразу приводим к миллисекундам, т.к. в настройках в минутах
        if (period > 0)
        {
            preordersUpdateTimer = new Timer();
            preordersUpdateTimer.schedule(new TimerTask() 
            {
                public void run()
                {
                    requestPreliminaryOrders(PN_UPDATE_PREORDERS_COUNT);
                }
            }, period, period);
        } 
    }
    
    private void registerNetworkNotifiers()
    {
        Connection.getConnection().setPacketListener(Packet.LOGIN_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet) 
            {
                LoginResponce responce = (LoginResponce)packet;
                
                if(responce.getAnswer().equals(LoginResponce.ANSWER_OK))
                {
                    //Сохраняем данные
                    runtimeData.setSrvID(responce.getSrvID());
                    runtimeData.setPeopleID(responce.getPeopleID());
                    runtimeData.setGUID(responce.getGUID());

                    //Открываем смену
                    openRelay();
                    
                    //Send software version
                    sendSoftwareVersion();
                    
                    //Запрашиваем PPC настройки
                    requestPPCSettings();
                    
                    //Помечаем индикатор связи что есть связь и выводим текст в метке
                    setStateLabel(responce.getAnswer());
                    setState(CONNECTED_STATE);
                    
                    //Запускаем обновление количества пред. заказов
                    startPreordersUpdateTimer();
                }
                else
                {
                    //Сбрасываем соединение
                    Connection.getConnection().stop();
                    
                    //Помечаем индикатор связи что неудалось залогинится
                    setState(LOGIN_ERROR_STATE);
                            
                    //Не удалось залогинится -выводим текст
                    setStateLabel(responce.getAnswer());
                }
            } 
        });
        
        Connection.getConnection().setPacketListener(Packet.SETTINGSXML_RESPONSE, new Connection.PacketNotifier() {
            public void incomingPacket(Packet packet) 
            {
                SettingsXML responce = (SettingsXML)packet;
                
                IMAPMIDlet.getMidlet().getRuntimeData().setCheckNoSubOrderForClose(responce.settingsData.checkNoSubOrderForClose);
                
                //Сохраняем полученные данные
                orderManager.setT(responce.settingsData.T1, responce.settingsData.T2, responce.settingsData.T3);
                if (responce.settingsData.maxOrdersCount != -1)
                {
                    orderManager.setMaxOrdersCount(responce.settingsData.maxOrdersCount);
                }
                
                
                //Чистим стоянкие если не совпал класс водителя
                if (IMAPMIDlet.getMidlet().getPositionManager().getUIDInf() != responce.settingsData.autoTariffClassUID)
                {       
                    IMAPMIDlet.getMidlet().getPositionManager().setUIDInf(responce.settingsData.autoTariffClassUID);
                    IMAPMIDlet.getMidlet().getPositionManager().setLastUpdate(0);
                }

                //Обновляем версию
                if ((responce.settingsData.javaVersion != null) && (responce.settingsData.link != null))
                {
                    try
                    {
                        double version = Double.parseDouble(responce.settingsData.javaVersion);
                        String temp = IMAPMIDlet.getMidlet().getMidletVersion();
                        double selfVersion = Double.parseDouble(temp);

                        if (selfVersion < version)
                        {
                            //Сбрасываем соединение
                            Connection.getConnection().stop();

                            //Отображаем форму обновления
                            showUpdateForm(responce.settingsData.link);
                        }
                    }catch(Exception e){}
                }
            }
        });
        
        Connection.getConnection().setPacketListener(Packet.PPCSETTINGS_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet) 
            {
                PPCSettingsResponce responce = (PPCSettingsResponce)packet;
                
                //Сохраняем полученные данные
                orderManager.setT(responce.getT1(), responce.getT2(), responce.getT3());
                if (responce.getMaxOrdersCount() != -1)
                {
                    orderManager.setMaxOrdersCount(responce.getMaxOrdersCount());
                }
                
                
                //Чистим стоянкие если не совпал класс водителя
                if (IMAPMIDlet.getMidlet().getPositionManager().getUIDInf() != responce.getAutoTariffClassUID())
                {       
                    IMAPMIDlet.getMidlet().getPositionManager().setUIDInf(responce.getAutoTariffClassUID());
                    IMAPMIDlet.getMidlet().getPositionManager().setLastUpdate(0);
                }

                //Обновляем версию
                if ((responce.getJavaVersion() != null) && (responce.getLink() != null))
                {
                    try
                    {
                        double version = Double.parseDouble(responce.getJavaVersion());
                        String temp = IMAPMIDlet.getMidlet().getMidletVersion();
                        double selfVersion = Double.parseDouble(temp);

                        if (selfVersion < version)
                        {
                            //Сбрасываем соединение
                            Connection.getConnection().stop();

                            //Отображаем форму обновления
                            showUpdateForm(responce.getLink());
                        }
                    }catch(Exception e){}
                }
            }
        });
        
        Connection.getConnection().setPacketListener(Packet.RELAY_COMMUNICATION_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet) 
            {
                RelayCommunicationResponce responce = (RelayCommunicationResponce)packet;
                
                if (responce.getRelayCommunicationType().equals(RelayCommunicationResponce.REGISTER_TYPE))
                {
                    if (responce.getRelayAnswerType().equals(RelayCommunicationResponce.AT_INVALID_CALLSIGN) ||
                        responce.getRelayAnswerType().equals(RelayCommunicationResponce.AT_OUT_OF_SEASON) ||
                        responce.getRelayAnswerType().equals(RelayCommunicationResponce.AT_DRIVER_IS_BLOCKED))
                    {
                        //Сбрасываем соединение
                        Connection.getConnection().stop();

                        //Помечаем индикатор связи что неудалось залогинится
                        setState(LOGIN_ERROR_STATE);

                        //Не удалось залогинится -выводим текст
                        setStateLabel(responce.getRelayAnswerType());
                    }
                    else
                    {
                        //Дозапрашиваем заказы
                        requestOrders();

                        //Запрашиваем текущее состояние
                        requestPosition();

                        //Запрашиваем баланс
                        requestBalance();
                    }
                }
                else if (responce.getRelayCommunicationType().equals(RelayCommunicationResponce.UNREGISTER_TYPE))
                {
                    //Сбрасываем соединение
                    Connection.getConnection().stop();

                    //Помечаем индикатор связи что закрыли смену
                    setState(LOGIN_ERROR_STATE);

                    //выводим текст
                    setStateLabel("relay_closed");
                }
            }
        });
        
        Connection.getConnection().setPacketListener(Packet.CSBALANCE_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet) 
            {
                GetCSBalanceResponce responce = (GetCSBalanceResponce)packet;
                
                //Обновляем текст с балансом
                String tmp = StringUtils.replace(balanceText, "?", responce.getSum());
                balanceLabel.setText(tmp);
                balanceLabel.repaint();
                
                //Отображаем баланс - если надо
                if (showBalance)
                {
                    Message message = new Message(tmp); 
                    message.setTimeout(SHOW_INFO_TIMEOUT);
                    IMAPMIDlet.getMidlet().getMessageManager().newMessage(message);
                } 
                showBalance = true; 
            }
        });
        
        Connection.getConnection().setPacketListener(Packet.DRIVER_BALANCE_CHANGED_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet) 
            {
                DriverBalanceChange responce = (DriverBalanceChange)packet;
                
                //Обновляем текст с балансом
                balanceLabel.setText(StringUtils.replace(balanceText, "?", responce.getAmount()));
                balanceLabel.repaint();
            }
        });
        
        Connection.getConnection().setPacketListener(Packet.REGISTER_ON_TAXI_PARKING_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet)
            {
                RegisterOnTaxiParkingResponce responce = (RegisterOnTaxiParkingResponce)packet;
                if (responce.getResult().equals(RegisterOnTaxiParkingResponce.RESULT_DONE))
                {
                    setStateLabel(responce.getParkingName() + ": " + responce.getNumberInQueue());
                    
                    //play sound if first in queue
                    if (responce.getNumberInQueue() == 1) {
                        NotificationManager.getNotificationManager().event(NotificationManager.FIRST_IN_QUEUE);
                    }
                }
            }
        });

        Connection.getConnection().setPacketListener(Packet.UNREGISTER_ON_TAXI_PARKING_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet)
            {
                 UnRegisterOnTaxiParkingResponce responce = (UnRegisterOnTaxiParkingResponce)packet;
                if (responce.getUnregistered() == UnRegisterOnTaxiParkingResponce.RESULT_OK)
                {
                    setStateLabel(LoginResponce.ANSWER_OK);
                }
            }
        });
        
        Connection.getConnection().setPacketListener(Packet.DRIVER_PARKING_POSITION_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet)
            {
                DriverParkingPositionResponce responce = (DriverParkingPositionResponce)packet;
                if (responce.getRegisteredOnParking() != DriverParkingPositionResponce.DRIVER_UNREGISTERED)
                {
                    setStateLabel(IMAPMIDlet.getMidlet().getPositionManager().getNameByID(responce.getUID()) + ": " + responce.getQueue());
                }
            }
        });

        Connection.getConnection().setPacketListener(Packet.SRV_MESSAGE_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet)
            {
                serverErrorAction("server_stopped");
            }
        });
        
        Connection.getConnection().setPacketListener(Packet.SERVER_ERROR_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet)
            {
                serverErrorAction("server_error");
            }
        });
        
        Connection.getConnection().setConnectionErrorListener(new Connection.ConnectionErrorListener()
        {
            public void connectionError(int code)
            {
                //Обновляем индикатор состояния
                setState(NO_CONNECTION_STATE);

                //Перерисовать форму
                ScreenEngine.getEngine().getCurrent().repaint();
                
                //Запускаем таймер реконекта
                Connection.getConnection().startReconnectTimer();
            }
        });
        
        Connection.getConnection().setPacketListener(Packet.PREORDERS_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet) 
            {
                PreOrdersResponse responce = (PreOrdersResponse)packet;
                
                //Устанавливаем количество предзаказов в менеджере
                orderManager.setPreordersCount(responce.count());
                
                //Отображаем форму предзаказов - если мы их запрашивали
                if (responce.getPacketNumber() == PN_GET_PREORDERS)
                {
                    //Заполняем форму предзаказов
                    if (prelimList == null)
                    {
                        prelimList = new OrdersListForm("prelim", "prelim_order");
                    }
                    prelimList.clear();
                    for (int i = 0; i < responce.count(); ++i)
                    {
                        prelimList.addOrder(responce.getOrder(i));
                    }
                    prelimList.setCountToTitle(responce.count());

                    //Отображаем
                    ScreenEngine.getEngine().push(prelimList);
                }
            }
        });
        
        Connection.getConnection().setPacketListener(Packet.FILTERED_TAXI_PARKINGS_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet) 
            {
                FilteredTaxiParkingsResponce responce = (FilteredTaxiParkingsResponce)packet;
                if (responce.getReturnID() == FilteredTaxiParkingsResponce.RESULT_OK)
                {
                    if (runtimeData.getCurrentRegionFilter().equals(""))
                    {
                        filterLabel.setText("");
                    }
                    else
                    {
                        filterLabel.setText(filterLabelText + " " + runtimeData.getCurrentRegionFilter());
                    }
                    
                    if (isVisible())
                    {
                        repaint();
                    }
                }
            }
        });
    }
    
    private void registerListeners()
    {
        orderManager.setPreordersCountChangedListener(new OrderManager.PreordersCountChanged() 
        {
            public void preordersCountChanged(int count) 
            {
                prelimLabel.setText(prelimLabelText + "(" + count + ")");
                if (isVisible())
                {
                    repaint();
                }
            }
        });

        orderManager.setCountChangedListener(new OrderManager.CountChanged() 
        {
            public void countChanged(int[] counts) 
            {
                efirLabel.setText(efirLabelText + "(" + counts[0] + ")");
                currentLabel.setText(currentLabelText + "(" + counts[1] + ")");
                completeLabel.setText(completeLabelText + "(" + counts[2] + ")");
                
                //Обнавляем количества на самих формах
                if (efirList != null)
                {
                    efirList.setCountToTitle(counts[0]);
                }
                if (currentList != null)
                {
                    currentList.setCountToTitle(counts[1]);
                }
                if (completeList != null)
                {
                    completeList.setCountToTitle(counts[2]);
                }
                
                if (isVisible())
                {
                    repaint();
                }
            }
        });
        
        orderManager.setOrderEventsListener(this);
        
        messageManager.setCountChangedListener(new MessageManager.CountChanged() 
        {
            public void countChanged(int newMessagesCount, int totalMessagesCount) 
            {
                messagesLabel.setText(messagesLabelText + " (" + newMessagesCount + "/" + totalMessagesCount + ")");
                if (messagesList != null)
                {
                    messagesList.setCountToTitle(newMessagesCount, totalMessagesCount);
                }
                
                //Меняем иконку
                if (newMessagesCount > 0)
                {
                    messagesLabel.setIcon(iconesIcon.subImage(ICONS_SIZE, 0, ICONS_SIZE, ICONS_SIZE, true));
                }
                else
                {
                    messagesLabel.setIcon(iconesIcon.subImage(0, 0, ICONS_SIZE, ICONS_SIZE, true));
                }
                
                if (isVisible())
                {
                    repaint();
                }
            }
        });  
        
        messageManager.setMessageEventsListener(this);
    }
    
    private void serverErrorAction(String message)
    {
        //Останавливаем соединение
        Connection.getConnection().stop();

        //Помечаем индикатор как нет соединения
        setState(NO_CONNECTION_STATE);

        //выводим текст
        setStateLabel(message);

        //Перерисовать форму
        ScreenEngine.getEngine().getCurrent().repaint();        

        //Запускаем оповещение
        NotificationManager.getNotificationManager().event(NotificationManager.CONNECTION_ERROR);
    }
    
    public void newMessage(Message message)
    {
        if (messagesList != null)
        {
            messagesList.addMessage(message, 0);
        }
        
        //Отображаем сообщение
        ScreenEngine.getEngine().showMessage("new_message", message, message.getTimeout());
    }
    
    public void newOrder(Order order)
    {
        //Добавляем заказ в "эфир"
        if (efirList != null)
        {
            if (Settings.getSettings().getEfirSort() == Settings.ES_BYTIME || (!order.isAlien()))
            {
                efirList.addOrder(order, 0);
            }
            else
            {
                efirList.addOrderAfterOwn(order);
            }
        }
        
        //Показываем заказ - если он не из эфира        
        if (!order.isEfirOrder())
        {
            if (newOrderForm == null)
            {
                newOrderForm = new OrderForm("disp_order");
            }
            if (!ScreenEngine.getEngine().containsForm(newOrderForm)) {
                newOrderForm.setOrder(order);
                ScreenEngine.getEngine().push(newOrderForm);
            }
        } 
    }
        
    public void deleteOrder(Order order)
    {
        //Просто удалить заказ отовсюду
        if (efirList != null)
        {
            efirList.removeOrder(order);
        }
        if (currentList != null)
        {
            currentList.removeOrder(order);
        }
        if (completeList != null)
        {
            completeList.removeOrder(order);
        }
    }
        
    public void cancelOrder(Order order)
    {
        //Вызывается при отмене заказа
        if (efirList != null)
        {
            efirList.removeOrder(order);
        }
        if (currentList != null)
        {
            currentList.removeOrder(order);
        }
        if (completeList != null)
        {
            completeList.addOrder(order, 0);
        }
     
        //Выводим отмененный заказ
        if (canceledOrderForm == null)
        {
            canceledOrderForm = new OrderForm("canceled_order");
        }
        if (!ScreenEngine.getEngine().containsForm(canceledOrderForm)) {
            canceledOrderForm.setOrder(order);
            ScreenEngine.getEngine().push(canceledOrderForm);
        }
    }
        
    public void completeOrder(Order order)
    {
        //Когда пришел принудительный пакет то заказ выполнен
        if (efirList != null)
        {
            efirList.removeOrder(order);
        }
        if (currentList != null)
        {
            currentList.removeOrder(order);
        }
        if (completeList != null)
        {
            completeList.addOrder(order, 0);
        }
          
        //Выводим выполненый заказ
        if (completedOrderForm == null)
        {
            completedOrderForm = new OrderForm("order_completed");
        }
        if (!ScreenEngine.getEngine().containsForm(completedOrderForm)) {
            completedOrderForm.setOrder(order);
            ScreenEngine.getEngine().push(completedOrderForm);
        }
    }
        
    public void orderUpdated(Order order)
    {
        //Отправляем в нужную коллекцию
        if (state == Order.STATE_NEW)
        {
            if (currentList != null)
            {
                currentList.removeOrder(order);
            }
            if (completeList != null)
            {
                completeList.removeOrder(order);
            }
            if (efirList != null)
            {
                efirList.addOrder(order, 0);
            }
        }
        else if (state == Order.STATE_PERFORMING || state == Order.STATE_TAKEN)
        {
            if (efirList != null)
            {
                efirList.removeOrder(order);
            }
            if (completeList != null)
            {
                completeList.removeOrder(order);
            }
            if (currentList != null)
            {
                currentList.addOrder(order, 0);
            }  
        }
        else if (state == Order.STATE_PERFORMED || state == Order.STATE_MISSED || state == Order.STATE_CANCELLED)
        {
            if (efirList != null)
            {
                efirList.removeOrder(order);
            }
            if (currentList != null)
            {
                currentList.removeOrder(order);
            }
            if (completeList != null)
            {
                completeList.addOrder(order, 0);
            }
        }

        //Отображаем заказ
        if (orderChangedForm == null)
        {
            orderChangedForm = new OrderForm("do_order");
        }
        if (!ScreenEngine.getEngine().containsForm(orderChangedForm)) {
            if (order.getStatus() == Order.STATE_PERFORMING){
               orderChangedForm.setTitle("do_order"); 
            } else {
                orderChangedForm.setTitle("order_changed"); 
            }
            orderChangedForm.setOrder(order);
            ScreenEngine.getEngine().push(orderChangedForm);
        }
    }
    
    public void orderStateChanged(Order order)
    {
        //На "новый" состояние точно измениться не может - удаляем 
        if (efirList != null)
        {
            efirList.removeOrder(order);
        }
        
        //Проверяем куда добавлять, откуда удалять
        if (order.getStatus() == Order.STATE_PERFORMING || order.getStatus() == Order.STATE_TAKEN)
        {
            if (completeList != null)
            {
                completeList.removeOrder(order);
            }
            if (currentList != null)
            {
                currentList.addOrder(order, 0);
            }
        }
        else if (order.getStatus() == Order.STATE_PERFORMED || order.getStatus() == Order.STATE_MISSED || order.getStatus() == Order.STATE_CANCELLED)
        {
            if (currentList != null)
            {
                currentList.removeOrder(order);
            }
            if (completeList != null)
            {
                completeList.addOrder(order, 0);
            }
        }
    }
    
    private void openRelay()
    {
        byte[] body = PacketBuilder.createBodyRegisterOnRelay(Settings.getSettings().getCallsign(), true, runtimeData.getPeopleID());
        byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
        Connection.getConnection().send(data);
    }
    
    private void sendSoftwareVersion() {
        byte[] body = PacketBuilder.createVersionDeviceSoftware("2", PacketBuilder.DEVICE_SOFTWARE_VERSION, runtimeData.getPeopleID()); //"2" - is for Java
        byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
        Connection.getConnection().send(data);
    }
    
    private void requestPPCSettings()
    {
        byte[] body = PacketBuilder.createBodyGetPPCSettingsXML(runtimeData.getPeopleID());
        byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
        Connection.getConnection().send(data); 
    }
    
    private void requestOrders()
    {
        String filter = "AutoDriverID = "+ runtimeData.getPeopleID() +" AND Folder <> 23 AND Folder <> 24 AND Folder <> 25 AND Folder <> 26";
	byte[] body = PacketBuilder.createGetOrdersOfDriver(filter, runtimeData.getPeopleID());//createGetOrders(filter);
	byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
	Connection.getConnection().send(data);
    }
    
    private void requestBalance()
    {
        showBalance = false;
        
        byte[] body = PacketBuilder.createGetBalanceData(runtimeData.getPeopleID());
	byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
        Connection.getConnection().send(data);
    }

    private void requestPosition()
    {
        byte[] body = PacketBuilder.createBodyGetDriverParkingPosition(runtimeData.getPeopleID());
	byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(),
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
        Connection.getConnection().send(data);
    }
    
    private boolean requestPreliminaryOrders(int packetNumber)
    {
        byte[] body = PacketBuilder.createReqPreOrders(runtimeData.getPeopleID());
        byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(),
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body, packetNumber);
        return Connection.getConnection().send(data);
    }
    
    private void setStateLabel(String state)
    {
        stateLabel.setText(state);
        repaint(); 
    }
    
    private void lookAction()
    {
        if (getFocused() == efirLabel)
        {
            showEfirOrdersList();
        }
        else if (getFocused() == prelimLabel)
        {
            showPreliminaryOrders();
        }
        else if (getFocused() == currentLabel)
        {
            showCurrentOrdersList();
        }
        else if (getFocused() == completeLabel)
        {
            showCompleteOrdersList();
        }
        else if (getFocused() == messagesLabel)
        {
            showMessagesList();
        }
    }
    
    private void showEfirOrdersList()
    {
        if (efirList == null)
        {
            efirList = new OrdersListForm("efir", "order_from_efir");
        }
        
        //Заново заполняем
        efirList.clear();
        Vector orders = orderManager.getEfirOrders();
        if (Settings.getSettings().getEfirSort() == Settings.ES_BYTIME)
        {
            for (int i = 0; i < orders.size(); ++i)
            {
                efirList.addOrder((Order)orders.elementAt(i));
            }
        }
        else if (Settings.getSettings().getEfirSort() == Settings.ES_ALIEN_BOTTOM)
        {
            //Сначала свои
            for (int i = 0; i < orders.size(); ++i)
            {
                if (!((Order)orders.elementAt(i)).isAlien())
                {
                    efirList.addOrder((Order)orders.elementAt(i));
                }
            }
            
            //Потом чужие
            for (int i = 0; i < orders.size(); ++i)
            {
                if (((Order)orders.elementAt(i)).isAlien())
                {
                    efirList.addOrder((Order)orders.elementAt(i));
                }
            }
        }
        efirList.setCountToTitle(orders.size());

        ScreenEngine.getEngine().push(efirList);
    }
    
    private void showPreliminaryOrders()
    {        
        //Запрашиваем пред. заказы
        if (requestPreliminaryOrders(PN_GET_PREORDERS))
        {
            //Пока идет запрос показываем сообщение
            ScreenEngine.getEngine().showMessageBox("message", (new Label("preorders_requesded")).getText(), 5000);
        }
    }
    
    private void showCurrentOrdersList()
    {
        if (currentList == null)
        {
            currentList = new OrdersListForm("current", "current");
        }
        
        //Заново заполняем
        currentList.clear();
        Vector orders = orderManager.getCurrentOrders();
        for (int i = 0; i < orders.size(); ++i)
        {
            currentList.addOrder((Order)orders.elementAt(i));
        }
        currentList.setCountToTitle(orders.size());

        ScreenEngine.getEngine().push(currentList);
    }
    
    private void showCompleteOrdersList()
    {
        if (completeList == null)
        {
            completeList = new OrdersListForm("complete", "complete", new CompletedOrderListRenderer()); 
        }
        
        //Заново заполняем
        completeList.clear();
        Vector orders = orderManager.getCompleteOrders();
        for (int i = 0; i < orders.size(); ++i)
        {
            completeList.addOrder((Order)orders.elementAt(i));
        }
        completeList.setCountToTitle(orders.size());

        ScreenEngine.getEngine().push(completeList);
    }
    
    private void showMessagesList()
    {
        if (messagesList == null)
        {
            messagesList = new MessagessListForm(iconesIcon.subImage(0, 0, ICONS_SIZE, ICONS_SIZE, true), 
                                                 iconesIcon.subImage(ICONS_SIZE, 0, ICONS_SIZE, ICONS_SIZE, true));
        }
        
        //Заново заполняем
        messagesList.clear();
        Vector messages = messageManager.getAllMessages();
        int unreadCount = 0;
        for (int i = 0; i < messages.size(); ++i)
        {
            if (!((Message)messages.elementAt(i)).isRead())
            {
                ++unreadCount;
            }
            messagesList.addMessage((Message)messages.elementAt(i));
        }
        messagesList.setCountToTitle(unreadCount, messages.size());
        
        ScreenEngine.getEngine().push(messagesList);
    }
    
    private void showMenuForm()
    {
        if (menuForm == null)
        {
            menuForm = new MenuForm();
        }
        
        ScreenEngine.getEngine().push(menuForm);
    }
    
    private void showUpdateForm(String updateLink)
    {
        if (updateForm == null)
        {
            updateForm = new UpdateForm();
        }
        
        //Устанавливаем ссылку обновления
        updateForm.setUpdateLink(updateLink);
        
        ScreenEngine.getEngine().push(updateForm);
    }
    
    public void keyPressed(int keyCode)
    {
        int game = Display.getInstance().getGameAction(keyCode);
        if(game == Display.GAME_DOWN && getFocused() == messagesLabel)
        {
            scrollComponentToVisible(balanceLabel);
        }
        
        super.keyPressed(keyCode);
      
        
    }
}
